#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"


int main(int argc, const char* argv[])
{
    printf("hello v3sAppLed 20240427\r\n");
    char rdBuf[100] = {0};
    char wrBuf[100] = {0};
    if (argc != 4 || (strlen(argv[3]) == 0)) {
        printf("input para wrong\r\n");
        return -1;
    }
    const char* fileName = argv[1];
    int fd = open(fileName, O_RDWR);
    if (fd < 0) {
        printf("opening [%s] error with %d\r\n", fileName, fd);
        return -2;
    }
    printf("opened [%d]\r\n");

    if (atoi(argv[2]) == 1) {
        int ret = read(fd, rdBuf, 50);
        if (ret >= 0) {
            printf("read from [%d] with [%s]\r\n", ret, rdBuf);
        } else {
            printf("read from [%d] failed\r\n", ret);
        }
    }

    if (atoi(argv[2]) == 2) {
        int ret = write(fd, argv[3], strlen(argv[3]));
        if (ret >= 0) {
            printf("writr to [%d] with [%s]\r\n", ret, argv[3]);
        } else {
            printf("read from [%d] failed\r\n", ret);
        }
    }

    if (atoi(argv[2]) == 3) {
        int ret = 0;
        while(ret == 0) {
            write(fd, "1", 1);
            usleep(400 * 1000);
            write(fd, "0", 1);
            usleep(100 * 1000);
        }
        printf("write failed with %d\r\n", ret);
    }

    return close(fd);
}